package com.authine.cloudpivot.common.extension.utils;

import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.idsmanager.dingdang.jwt.DingdangUserRetriever;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author hxd
 * @Date 2021/11/10 11:00
 * @Description
 **/
@Slf4j
public class SsoUtils {
    //测试
//    private static final String PublicKey = "{\"kty\":\"RSA\",\"kid\":\"3577883829544602760\",\"alg\":\"RS256\",\"n\":\"nbCSRHGcNyOVxiBxEYPlPxVbdxBI-Sqnb9jNAdWdj2XKg4VUIWAniTbNrQ1nrTAWQO5s0s2iIf7vx3MVlB6FF-PyRmwzI3frgrnivwNF4df-RsL7P5I3aSfoMND25XB70oqZf_LfiBKx-FHjvd2PQdmTOpyKG7lNlMGvEGAmyzAX0A4u3gjqkCizr9_stNnqic1usRQRegzuSNBtL_43Ev7eMOzszYDAm-7Uj5Gjx8NmAHEn76Q9PTuhhtLMPKoIm6htcFxQNlGX9JjpDvkLY21lye_X1yqnvCMoe0s6qzXztQe-qOTGqPQUjnBXCbSV-myu76h2gaIDA75dmgqT1Q\",\"e\":\"AQAB\"}";
    //正式
    private static final String PublicKey = "{\"kty\":\"RSA\",\"kid\":\"5305997583449771783\",\"alg\":\"RS256\",\"n\":\"1gEzE5Nty2-UhqJJi10ySba5Tj_TmsKYY6B8y1q41EE6sPwRwOBXeAZUzvLl56XYRAolpE2Wndmh3WbKKhXj8tCV5Tf3mK8ZtfkaML6GSq1uvyLM3K7v-cR8gI_6-DT3Qh-Bi1-rglrQSgFfKvUpLzvQ6kdfcaYhnPmBaloVJ69zyi-5LRK9Ghp1E6gjU0JDIrYh6DJAGf-tc6nUzI9qVUh09sxpBP-IyrHFBwt58TjBK7S-aUqQktzo2K9H3xf5TvTdUiZN-V1CsLHUVshc-WQek47SPoqaKiEjuZot_mm6P_nxHQ_-jW27lDJnwOKjdJIK4AiI7tJwohmvaQoGWw\",\"e\":\"AQAB\"}";


    public static String getUsername(String token){

        return getUser(token).getUsername();
    }

    private static DingdangUserRetriever.User getUser(String token){


        DingdangUserRetriever.User user = null;
        try {
            log.info("\n=========================获取 idaas jwt  token :{}", token);
            DingdangUserRetriever retriever = new DingdangUserRetriever( token,PublicKey);

            //2.获取用户信息
            user = retriever.retrieve();
            log.info("\n=========================解析到idaas jwt user :{}", JSON.toJSONString(user));
        } catch (Exception e) {
            log.warn("Retrieve SSO user failed", e);
            throw new BizException("jwt 解析失败");
        }

        if (user == null) {
            log.warn("jwt 解析失败,user为null");
            throw new BizException("jwt 解析失败,user为null");
        }
        return user;
    }

}
